package com.geek.video.utils;

import com.geek.video.exception.GlobalException;
import com.geek.video.utils.functionalinterface.ThrowExceptionBiFunction;
import com.geek.video.utils.functionalinterface.ThrowExceptionFunction;
import com.geek.video.utils.functionalinterface.ThrowExceptionRunnable;

/**
 * 函数式编程工具类
 *
 * @author Steven
 */
public class FunctionalUtil {

    public static void retryFunction(ThrowExceptionRunnable runnable, int time) {

        while (true) {
            try {
                runnable.run();
                return;
            } catch (Exception e) {
                time--;
                if (time <= 0) {
                    throw new GlobalException(e.getMessage());
                }
            }
        }
    }

    public static <T, R> R retryFunction(ThrowExceptionFunction<T, R> function, T t, int time) {

        while (true) {
            try {
                return function.apply(t);
            } catch (Exception e) {
                time--;
                if (time <= 0) {
                    throw new GlobalException(e.getMessage());
                }
            }
        }
    }

    public static <T, U, R> R retryFunction(ThrowExceptionBiFunction<T, U, R> function, T t, U u, int time) {

        while (true) {
            try {
                return function.apply(t, u);
            } catch (Exception e) {
                time--;
                if (time <= 0) {
                    throw new GlobalException(e.getMessage());
                }
            }
        }
    }
}
